package com.lagou.edu.factory;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import com.lagou.edu.annotations.Autowired;
import com.lagou.edu.annotations.Component;
import com.lagou.edu.annotations.Transactional;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.reflections.Reflections;
import org.reflections.scanners.*;
import org.reflections.util.ConfigurationBuilder;

import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.*;

/**
 * @author 应癫
 *
 * 工厂类，生产对象（使用反射技术）
 */
public class BeanFactory {

    /**
     * 任务一：读取解析xml，通过反射技术实例化对象并且存储待用（map集合）
     * 任务二：对外提供获取实例对象的接口（根据id获取）
     */

    private static Map<String,Object> map = new HashMap<>();  // 存储对象
    public static String basePackage = "com.lagou.edu";

    public static void initAnnotations() throws IllegalAccessException, InstantiationException {
        //扫描@Component 反射生成实例，如果类@Transactional 则为实例创建代理对象
        //反射生成实例，属性注入，如果属性@Autowired 则查看是否已有实例，有则set,无则反射实例化后set
        Reflections reflections = new Reflections(new ConfigurationBuilder()
                .forPackages(basePackage)
                .addScanners(new SubTypesScanner())
                .addScanners(new FieldAnnotationsScanner())
                .addScanners(new MethodAnnotationsScanner())
                .addScanners(new MethodParameterScanner())
                .addScanners(new MethodParameterNamesScanner())
                .addScanners(new ResourcesScanner())
        );
        //实例化
        Set<Class<?>> components = reflections.getTypesAnnotatedWith(Component.class);
        for (Class<?> item : components) {
            pushMap(item);
        }
        //注入
        map.entrySet().stream().forEach(item->{
            Class<?> component = item.getValue().getClass();
            new ArrayList<>(Arrays.asList(component.getDeclaredFields())).stream().forEach(field->{
                Autowired autowired = field.getAnnotation(Autowired.class);
                if(ObjectUtil.isNotEmpty(autowired)){
                    String fieldBeanId = null;
                    if(field.getType().isInterface()){
                        fieldBeanId = ObjectUtil.isNotEmpty(autowired.name()) ? autowired.name() : StrUtil.lowerFirst(field.getType().getSimpleName());
                    }else{
                        fieldBeanId = ObjectUtil.isNotEmpty(autowired.name()) ? autowired.name():field.getName();
                    }
                    ReflectUtil.setFieldValue(item.getValue(),field,map.get(fieldBeanId));
                }
            });
        });
        //事务动态代理
        map.entrySet().stream().forEach(item->{
            Transactional transactional = null;
            transactional = item.getValue().getClass().getAnnotation(Transactional.class);
            if(ObjectUtil.isNotEmpty(transactional)){
                String componentId = ProxyFactory.class.getAnnotation(Component.class).value();
                componentId = ObjectUtil.isNotEmpty(componentId) ? componentId :StrUtil.lowerFirst(ProxyFactory.class.getSimpleName());
                ProxyFactory proxyFactory = (ProxyFactory) map.get(componentId);
                map.put(item.getKey(),proxyFactory.getCglibProxy(item.getValue()));
            }
        });

        System.out.println(StrUtil.toString(map));

    }

    private static void pushMap(Class<?> item) throws InstantiationException, IllegalAccessException {
        Component component = item.getAnnotation(Component.class);
        String beanId = null;
        if(item.getInterfaces().length > 0){
            beanId = ObjectUtil.isNotEmpty(component.value()) ? component.value():StrUtil.lowerFirst((item.getInterfaces().clone())[0].getSimpleName());
        }else{
            beanId = ObjectUtil.isNotEmpty(component.value()) ? component.value(): StrUtil.lowerFirst(item.getSimpleName());
        }
        if(!map.containsKey(beanId)){
            Object instance = item.newInstance();
            map.put(beanId,instance);
        }
    }


    public static void initXmlBean(){
        // 任务一：读取解析xml，通过反射技术实例化对象并且存储待用（map集合）
        // 加载xml
        InputStream resourceAsStream = BeanFactory.class.getClassLoader().getResourceAsStream("beans.xml");
        // 解析xml
        SAXReader saxReader = new SAXReader();
        try {
            Document document = saxReader.read(resourceAsStream);
            Element rootElement = document.getRootElement();
            List<Element> beanList = rootElement.selectNodes("//bean");
            for (int i = 0; i < beanList.size(); i++) {
                Element element =  beanList.get(i);
                // 处理每个bean元素，获取到该元素的id 和 class 属性
                String id = element.attributeValue("id");        // accountDao
                String clazz = element.attributeValue("class");  // com.lagou.edu.dao.impl.JdbcAccountDaoImpl
                // 通过反射技术实例化对象
                Class<?> aClass = Class.forName(clazz);
                Object o = aClass.newInstance();  // 实例化之后的对象

                // 存储到map中待用
                map.put(id,o);

            }

            // 实例化完成之后维护对象的依赖关系，检查哪些对象需要传值进入，根据它的配置，我们传入相应的值
            // 有property子元素的bean就有传值需求
            List<Element> propertyList = rootElement.selectNodes("//property");
            // 解析property，获取父元素
            for (int i = 0; i < propertyList.size(); i++) {
                Element element =  propertyList.get(i);   //<property name="AccountDao" ref="accountDao"></property>
                String name = element.attributeValue("name");
                String ref = element.attributeValue("ref");

                // 找到当前需要被处理依赖关系的bean
                Element parent = element.getParent();

                // 调用父元素对象的反射功能
                String parentId = parent.attributeValue("id");
                Object parentObject = map.get(parentId);
                // 遍历父对象中的所有方法，找到"set" + name
                Method[] methods = parentObject.getClass().getMethods();
                for (int j = 0; j < methods.length; j++) {
                    Method method = methods[j];
                    if(method.getName().equalsIgnoreCase("set" + name)) {  // 该方法就是 setAccountDao(AccountDao accountDao)
                        method.invoke(parentObject,map.get(ref));
                    }
                }

                // 把处理之后的parentObject重新放到map中
                map.put(parentId,parentObject);
            }

        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    // 任务二：对外提供获取实例对象的接口（根据id获取）
    public static Object getBean(String id) {
        return map.get(id);
    }

}
